package com.dy.course.service.impl;

import java.util.List;

import javax.transaction.Transactional;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.dy.course.common.BaseException;
import com.dy.course.common.BaseService;
import com.dy.course.common.Constant;
import com.dy.course.entity.ModifyUserInfo;
import com.dy.course.entity.RegisterInfo;
import com.dy.course.entity.UpdateOrCreateUser;
import com.dy.course.entity.UserInfo;
import com.dy.course.model.User;
import com.dy.course.service.INameService;
import com.dy.course.service.IUserService;
import com.dy.course.util.Md5SaltTool;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Service
public class UserService extends BaseService<User> implements IUserService {

	@Autowired
	private INameService nameService;
	
//	@Autowired
//	private CacheManager cache;

	@Override
	public void register(RegisterInfo registerInfo) {
		logger.info("【注册服务】参数信息,registerInfo=" + JSON.toJSONString(registerInfo));
		User user = new User();
		Example example = new Example(User.class);
		example.createCriteria().andEqualTo("phone", registerInfo.getPhone());
		int count = getMapper().selectCountByExample(example);
		if (count > 0) {
			logger.info("注册异常,手机号码已经注册registerInfo=" + JSON.toJSONString(registerInfo));
			throw new BaseException(Constant.Code.USER_PHONE_EXISTS, "手机号码已经注册", null);
		}
		example.clear();
		example.createCriteria().andEqualTo("workNo", registerInfo.getWorkNo()).andEqualTo("universityId",registerInfo.getUniversityId());
		int count2 = getMapper().selectCountByExample(example);
		if(count2 > 0){
			logger.info("注册异常,学号/工号已被注册registerInfo=" + JSON.toJSONString(registerInfo));
			throw new BaseException(Constant.Code.USER_WORK_NO_EXISTS,"学号/工号已被注册",null);
		}

		String encryptedPwd = null;
		BeanUtils.copyProperties(registerInfo, user);
		//密码加密
		encryptedPwd = Md5SaltTool.getEncryptedPwd(user.getPassword());
		user.setPassword(encryptedPwd);
		getMapper().insertSelective(user);

	}

	@Override
	public User login(UpdateOrCreateUser user) {
		logger.info("【登录】参数信息,user=" + JSON.toJSONString(user));
		Example example = new Example(User.class);
		example.createCriteria().andEqualTo("phone", user.getPhone());
		List<User> dbUserList = getMapper().selectByExample(example);
		if (dbUserList.isEmpty()) {
			logger.info("用户不存在,参数信息,user=" + JSON.toJSONString(user));
			throw new BaseException(Constant.Code.SELECT_ERROR, "账号不存在", null);
		}

		User dbUser = dbUserList.get(0);
		if (!Md5SaltTool.validPassword(user.getPassword(), dbUser.getPassword())) {
			throw new BaseException(Constant.Code.USER_NAME_OR_PASSWORD_NOT_CORRENT, "用户或者密码不正确", null);
		}
		dbUser.setUrl(nameService.getUrlName(dbUser.getPictureId()));
		dbUser.setUniversityName(nameService.getDepartmentName(dbUser.getUniversityId()));
		dbUser.setFacultyName(nameService.getDepartmentName(dbUser.getFacultyId()));
		dbUser.setMajorName(nameService.getDepartmentName(dbUser.getMajorId()));
		dbUser.setClassName(nameService.getDepartmentName(dbUser.getClassId()));
		dbUser.setPassword(null);
//		String jwtToken = Jwts.builder().setSubject(user.getPhone()).claim("roles", "user").setIssuedAt(new Date())
//	            .signWith(SignatureAlgorithm.HS256, "secretkey").compact();
//		cache.set(jwtToken, dbUser.getPhone(), Constant.KEY_EXPIRE_TIME);
		return dbUser;
	}

	@Transactional
	@Override
	public void resetPassword(ModifyUserInfo rpi) {
		logger.info("【重置密码】参数信息,rpi=" + JSON.toJSONString(rpi));
		/*
		 * @@@ 非业务验证: 数据长度验证,非空性验证,相等验证
		 * 
		 * 
		 */
		User user = new User();
		BeanUtils.copyProperties(rpi, user);
		Example example = new Example(User.class);
		example.createCriteria().andEqualTo("phone", user.getPhone());
		List<User> dbUserList = getMapper().selectByExample(example);
		if (dbUserList.isEmpty()) {
			logger.error("【】用户不存在,参数信息,user=" + JSON.toJSONString(user));
			throw new BaseException(Constant.Code.USER_NOT_EXIST, "账号不存在", null);
		}
		//密码加密
		String encryptedPwd = Md5SaltTool.getEncryptedPwd(user.getPassword());
		User passwordUser = new User();
		passwordUser.setPassword(encryptedPwd);
		int count = getMapper().updateByExampleSelective(passwordUser, example);
		if(count < 1){
			logger.error("【】用户不存在,参数信息,rpi=" + JSON.toJSONString(rpi));
			throw new BaseException(Constant.Code.INSERT_ERROR, "数据不存在或者已经被删除", null);
		}
	}

	@Override
	public void update(UpdateOrCreateUser user) {
		logger.info("【修改用户信息】参数信息,user=" + JSON.toJSONString(user));
		User updateUser = new User();
		BeanUtils.copyProperties(user, updateUser);
		logger.info("【修改用户信息】参数信息,updateUser=" + JSON.toJSONString(updateUser));
		getMapper().updateByPrimaryKeySelective(updateUser);
	}

	@Override
	public List<User> qurey(UserInfo user) {
		logger.info("【查詢用戶】参数信息,user=" + JSON.toJSONString(user));
		User u = new User();
		BeanUtils.copyProperties(user, u);
		Example example = new Example(User.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("name", user.getName());
		criteria.andEqualTo("workNo", user.getWorkNo());
		criteria.andEqualTo("classId", user.getClassId());
		criteria.andEqualTo("facultyId", user.getFacultyId());
		criteria.andEqualTo("majorId", user.getMajorId());
		criteria.andEqualTo("universityId", user.getUniversityId());
		super.startPage(user);
		List<User> list = getMapper().selectByExample(example);
		if (list.size() <= 0) {
			throw new BaseException(Constant.Code.SELECT_ERROR, "数据不存在或者已经删除,请刷新重试", null);
		}
		return list;
	}

	@Override
	public User qureyById(UpdateOrCreateUser user) {
		logger.info("【查询用户】参数信息,user=" + JSON.toJSONString(user));
		Example example = new Example(User.class);
		example.createCriteria().andEqualTo("id", user.getId());
		List<User> dbUserList = getMapper().selectByExample(example);
		User dbUser = dbUserList.get(0);
		dbUser.setUrl(nameService.getUrlName(dbUser.getPictureId()));
		dbUser.setUniversityName(nameService.getDepartmentName(dbUser.getUniversityId()));
		dbUser.setFacultyName(nameService.getDepartmentName(dbUser.getFacultyId()));
		dbUser.setMajorName(nameService.getDepartmentName(dbUser.getMajorId()));
		dbUser.setClassName(nameService.getDepartmentName(dbUser.getClassId()));
		dbUser.setPassword(null);
		return dbUser;
	}
}
